# -*- coding: utf-8 -*-
import sys
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
from urllib.parse import urlencode
import requests,json
from common.helper import Helper


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "健康保重大疾病保险（少儿版）"

    # 生成产品数据
    def genProductInfo(self):
        plan = {
            "planA":{
                # 年龄段
                "year": [str(i) for i in range(0, 19)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["300000"],
                # 保障期限
                "expire": ["终身"],
                # 交费间隔
                "interval": ["5", "10", "15", "20", "30"],
                # 交费类型
                "payType": ["年交"],
                # 恶性肿瘤保险金
                "seriousCancer": ["0", "1"],
                # 特别保险金
                "specialCare": ["1"]
            },
            "planB":{
                # 年龄段
                "year": [str(i) for i in range(0, 19)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["400000","500000","600000","700000","800000"],
                # 保障期限
                "expire": ["终身"],
                # 交费间隔
                "interval": ["5", "10", "15", "20", "30"],
                # 交费类型
                "payType": ["年交"],
                # 恶性肿瘤保险金
                "seriousCancer": ["0", "1"],
                # 特别保险金
                "specialCare": ["1"]
            }
        }
        for k in plan:
            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["money"], plan[k]["expire"], plan[k]["interval"], plan[k]["payType"],
                             plan[k]["seriousCancer"], plan[k]["specialCare"]):
                data = Helper.formatProductInfo(plan[k], v)
                data["seriousCancer"] = data["money"] if data["seriousCancer"] == "1" else "0"
                data["specialCare"] = data["money"] if data["specialCare"] == "1" else "0"
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data))

    def requestJson(self, dt=None):
        birth = str(2020-int(dt["year"])) + "-01-01" if dt["year"] != "18" else "2002-04-12"
        sex = "0" if dt["gender"] == "M" else "1"
        period = dt["interval"]
        money = dt["money"]
        items = [{"dutyCode":"521001","dutyAmnt":money}]
        ext_item = {
            "specialCare":dt["specialCare"],
            "seriousCancer":dt["seriousCancer"]
        }
        for v in ext_item:
                if v == "specialCare" and ext_item[v] != "0":
                    items.append( {"dutyCode":"521002","dutyAmnt": money } )
                elif v == "seriousCancer" and ext_item[v] != "0":
                    items.append( {"dutyCode":"521003","dutyAmnt":money } )
        string = ""
        for item in items:
            string += json.dumps( item ) + ","
        string = string.strip(",")
        data = {
            "insuredsStr": '[{"birthday":"' + birth + '","sex":"' + sex + '","planInfos":[{"riskCode":"I164","mainRiskCode":"I164","planCode":"48","planPeriod":"终身","payType":"0","payEndYearFlag":"Y","payEndYear":' + period + ',"dutys":['+string+']}]}]',
            "isOrder": "0",
            "productID": "43",
        }

        payload = urlencode( data ).replace("+","")
        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)
        if r.status_code==200 and r.json()["data"]["data"]["premiun"]:

            price = Helper.decimalParse( r.json()["data"]["data"]["premiun"] )
            data ={
                "name":self.name,
                "id":dt["id"],
                "price":price

            }
            print( data )
            self.mysql.updatePrice( data )

        else:
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3

            }
            self.mysql.updateTask(data)
            print("\n/产品价格更新失败:%d*/"%dt["id"])

    def main(self):
        while True:
            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)
            self.requestJson(dt)
